<template>
  <div>
    <el-card shadow="always" v-loading="loading">
      <!-- <el-button type="primary" size="default" @click="addTrademark" icon="Plus" v-if="userStore.buttons.includes('btn.Trademark.add')"> -->
      <el-button type="primary" size="default" @click="addTrademark" icon="Plus" v-has="`btn.Trademark.add`">添加品牌</el-button>

      <el-table :data="tableData" border stripe style="margin: 10px 0">
        <el-table-column type="index" width="80" label="序号" align="center" />
        <el-table-column label="品牌名称" align="center" prop="tmName" />
        <el-table-column label="品牌logo" align="center">
          <template #default="{ row }">
            <div class="demo-image__preview">
              <el-image :src="row.logoUrl" fit="cover" style="width: 80px; height: 80px" :preview-src-list="[row.logoUrl]" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button type="warning" size="small" icon="Edit" @click="updateTrademark(row)" />

            <el-popconfirm title="是否确定删除该产品" confirmButtonText="确定" cancelButtonText="取消" @confirm="removeTradeMark(row.id)">
              <template #reference>
                <el-button type="danger" size="small" icon="Delete" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:currentPage="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        layout="prev, pager, next, jumper, ->,sizes, total"
        @current-change="currentChange"
        @size-change="sizeChange"
        :total="total"
        background
      />
    </el-card>

    <el-dialog :title="trademarkParams.id ? '修改品牌' : '添加品牌'" v-model="dialogFormVisible">
      <el-form style="width: 80%" :model="trademarkParams" :rules="rules" ref="formRef">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="trademarkParams.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <el-image v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, nextTick } from 'vue'
  import type { FormInstance, FormRules, UploadProps } from 'element-plus'
  import { reqHasTrademark, reqAddOrUpdateTradeMark, reqDeleteTrademark } from '@/api/product/trademark'
  import type { TradeMarkResponseData, Records, TradeMark } from '@/api/product/trademark/type'
  import { getElMessage } from '@/utils/message'
  // import useUserStore from '@/store/modules/user'

  // const userStore = useUserStore()
  const tableData = ref<Records>([])
  const pageNo = ref<number>(1)
  const limit = ref<number>(3)
  const total = ref<number>(0)
  const loading = ref<boolean>(false)
  const currentChange = (page: number) => {
    getData(page)
  }
  const sizeChange = (pageSize: number) => {
    limit.value = pageSize
    getData()
  }

  async function getData(pager = 1) {
    pageNo.value = pager
    loading.value = true
    let res: TradeMarkResponseData = await reqHasTrademark(pageNo.value, limit.value)
    if (res.code == 200) {
      total.value = res.data.total
      tableData.value = res.data.records
      loading.value = false
    }
  }

  onMounted(() => {
    getData()
  })

  const trademarkParams = reactive<TradeMark>({
    tmName: '',
    logoUrl: '',
  })
  function validateLogo(_rule: any, value: any, callback: any) {
    if (value) {
      callback()
    } else {
      callback(new Error('LOGO图片务必上传'))
    }
  }
  const rules = reactive<FormRules<TradeMark>>({
    tmName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
    logoUrl: [{ required: true, validator: validateLogo, message: '请选择产品图片', trigger: 'change' }],
  })
  const formRef = ref<FormInstance>()
  // 新增
  const dialogFormVisible = ref<boolean>(false)
  function addTrademark() {
    dialogFormVisible.value = true
    nextTick(() => {
      formRef.value?.resetFields()
      trademarkParams.id = 0
    })
  }
  function updateTrademark(row: TradeMark) {
    dialogFormVisible.value = true
    Object.assign(trademarkParams, row)
  }

  async function removeTradeMark(id: number) {
    const res = await reqDeleteTrademark(id)
    if (res.code === 200) {
      getElMessage('删除品牌成功')
      getData(pageNo.value)
    } else {
      getElMessage('删除品牌失败')
    }
  }

  async function confirm() {
    await formRef.value?.validate()
    let res: any = await reqAddOrUpdateTradeMark(trademarkParams)
    if (res.code === 200) {
      dialogFormVisible.value = false
      getElMessage(trademarkParams.id ? '修改品牌成功' : '添加品牌成功')
      getData(pageNo.value)
    } else {
      getElMessage(trademarkParams.id ? '修改品牌失败' : '添加品牌失败', 'error')
    }
  }

  const handleAvatarSuccess: UploadProps['onSuccess'] = (_response, uploadFile) => {
    trademarkParams.logoUrl = URL.createObjectURL(uploadFile.raw!)
    formRef.value?.clearValidate('logoUrl')
    // 图片上传成功，清楚图片校验(不需要nextTick，因为form已经存在了)
    // nextTick(() => {
    //   formRef.value?.clearValidate('logoUrl')
    // })
  }

  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
    //要求:上传文件格式png|jpg|gif 4M
    if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
      if (rawFile.size / 1024 / 1024 < 4) {
        return true
      } else {
        getElMessage('上传文件大小小于4M', 'error')
        return false
      }
    } else {
      getElMessage('上传文件格式务必PNG|JPG|GIF', 'error')
      return false
    }
  }
</script>

<style lang="scss" scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

  .demo-image__error .image-slot {
    font-size: 30px;
  }
  .demo-image__error .image-slot .el-icon {
    font-size: 30px;
  }
  .demo-image__error .el-image {
    width: 100%;
    height: 200px;
  }
</style>
